package org.webrtc;

import android.util.Log;

import androidx.annotation.Nullable;

/**
 * 接收从远端获取的编码数据
 */
public class MyVideoDecoder implements VideoDecoder, VideoSink, VideoDecoder.Callback {
    private static final String TAG = MyVideoDecoder.class.getSimpleName();

    private AndroidVideoDecoder androidVideoDecoder;
    private Callback nativeCallback;

    public MyVideoDecoder(String codecName, VideoCodecMimeType codecType, int colorFormat, @Nullable EglBase.Context sharedContext) {
        androidVideoDecoder = new AndroidVideoDecoder(new MediaCodecWrapperFactoryImpl(), codecName, codecType, colorFormat, sharedContext);
    }

    @Override
    public long createNativeVideoDecoder() {
        long ret = androidVideoDecoder.createNativeVideoDecoder();
        Log.i(TAG, "createNativeVideoDecoder(), ret: " + ret);
        return ret;
    }

    @Override
    public VideoCodecStatus initDecode(Settings settings, Callback callback) {
        Log.i(TAG, "initDecode()");
        nativeCallback = callback;
        return androidVideoDecoder.initDecode(settings, this);
    }

    @Override
    public VideoCodecStatus release() {
        Log.i(TAG, "release()");
        return androidVideoDecoder.release();
    }

    @Override
    public VideoCodecStatus decode(EncodedImage encodedImage, DecodeInfo decodeInfo) {
        Log.i(TAG, "decode()", new Exception("test"));
        return androidVideoDecoder.decode(encodedImage, decodeInfo);
    }

//    @Override
//    public boolean getPrefersLateDecoding() {
//        Log.i(TAG, "getPrefersLateDecoding()");
//        return androidVideoDecoder.getPrefersLateDecoding();
//    }

    @Override
    public String getImplementationName() {
        String name = androidVideoDecoder.getImplementationName();
        Log.i(TAG, "getImplementationName(), name: " + name);
        return name;
    }

    @Override
    public void onFrame(VideoFrame videoFrame) {
        VideoFrame.Buffer buffer = videoFrame.getBuffer();
        if (buffer instanceof VideoFrame.TextureBuffer) {
            Log.i(TAG, "onFrame(), VideoFrame.Buffer: " + ((VideoFrame.TextureBuffer)videoFrame.getBuffer()).getType());
        } else if (buffer instanceof VideoFrame.I420Buffer){
            Log.i(TAG, "onFrame(), VideoFrame.Buffer: " + ((VideoFrame.I420Buffer)videoFrame.getBuffer()));
        }
        androidVideoDecoder.onFrame(videoFrame);
    }

    @Override
    public void onDecodedFrame(VideoFrame videoFrame, Integer decodeTimeMs, Integer qp) {
        Log.i(TAG, "onDecodedFrame(), videoFrame: " + WebrtcToString.toString(videoFrame) + ", decodeTimeMs: " + decodeTimeMs + ", qp: " + qp, new Exception(""));
        if (nativeCallback != null) {
            nativeCallback.onDecodedFrame(videoFrame, decodeTimeMs, qp);
        }
    }
}
